<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
		<title></title>
		<script>
			window.onload = function() {
				var canvas = document.querySelector('canvas');
				canvas.width = document.documentElement.clientWidth;
				canvas.height = document.documentElement.clientHeight;
				//这里是做浏览器兼容,有这个方法则创建画笔,没有则不创建
				if (canvas.getContext) {
					var ctx = canvas.getContext('2d');
					var img = new Image();
					img.src = './imgs/scratch-card01.jpg';
					img.onload = function() {
						draw();
					}

					function draw() {
						var count = 0;
						ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
						//设置手指点击事件
						canvas.ontouchstart = function(ev) {
							ev = ev || event;
							var oTouch = ev.changedTouches[0];
							var x = oTouch.clientX;
							var y = oTouch.clientY;

							ctx.lineWidth = 40;
							ctx.lineCap = "round";
							ctx.lineJoin = "round";
							ctx.globalCompositeOperation = "destination-out"
							ctx.save();
							ctx.beginPath();
							ctx.moveTo(x, y);
							ctx.lineTo(x + 1, y + 1);
							ctx.stroke();
							ctx.restore();
						}
						//设置手指滑动事件
						canvas.ontouchmove = function(ev) {
							ev = ev || event;
							var oTouch = ev.changedTouches[0];
							var x = oTouch.clientX;
							var y = oTouch.clientY;

							ctx.save();
							ctx.lineTo(x, y);
							ctx.stroke();
							ctx.restore();
						}
						//设置手指拿起事件,并判断刮刮卡已经刮掉的面积是否大于50%,若真,则直接显示全图
						canvas.ontouchend = function() {
							var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
							var allPix = canvas.width * canvas.height;
							for (let i = 0; i < allPix; i++) {
								// 这里4*i的意思是一个像素点有rgba四个属性（0-255）,在加3就是a即透明度.
								if (imgData.data[4 * i + 3] === 0) {
									count++;
								}
							}
							if (count >= allPix / 2) {
								//当刮刮卡已经刮掉的面积大于50%,则直接设置透明度为0,显示里面的图
								canvas.style.opacity = 0;
							}
						}
						//当结束动画时，去除canvas动画，让用户能够操作li元素，后续可以在li添加多个页面
						canvas.addEventListener("transitionend", function() {
							this.remove();
						})
					}
				}
			}
		</script>
		<style>
			* {
				margin: 0;
				padding: 0;
			}

			.scratch-card {
				height: 100vh;
			}

			canvas {
				position: absolute;
				top: 0;
				left: 0;
				transition: 1.2s;
			}

			.scratch-card ul,
			ul>li {
				height: 100%;

			}

			.scratch-card ul>li {
				background: url(./imgs/scratch-card02.jpg) no-repeat;
				background-size: 100% 100%;
			}
		</style>
	</head>
	<body>
		<div class="scratch-card">
			<canvas>
				<span>您的浏览器不支持画布元素，请使用谷歌浏览器</span>
			</canvas>
			<ul>
				<li></li>
			</ul>
		</div>
	</body>
</html>
